package com.zyl.basis.syn;

/**
 * @author zhaoyl
 * @date 2024/5/27 16:55
 * @description 说明
 * 模拟买票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"小明").start();
        new Thread(station,"小红").start();
        new Thread(station,"小张").start();
    }
}

class BuyTicket implements Runnable{
    //票
    private int ticketsNums = 10;
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }
    }

    //synchronized同步的方法
    public synchronized void buy()  {
        //判断是否有票
        if (ticketsNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketsNums--);
    }
}
